package com.example.startscreen;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.util.ByteArrayBuffer;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import snt.com.webservice.Base64;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CameraActivity extends Activity {
	
	Bitmap photo;
	Bitmap mapPhoto;

	// za upload
	private static final String NAMESPACE = "http://213.149.97.23/MyWebServices"; // ovdje
																				// paziti
																				// da
																				// se
																				// ne
																				// doda
																				// poslednji
																				// slash!!!
	private static final String URL = "http://213.149.97.23/MyWebServices/FirstService.asmx";
	private static final String SOAP_ACTION = "http://213.149.97.23/MyWebServices/UploadEncodedString";
	private static final String METHOD_NAME = "UploadEncodedString";
	//
	private static final int CAMERA_REQUEST = 1888;
	private ImageView imageView;
	private TextView dateView;
	private TextView fileView;
	private TextView longitudeView;
	private TextView latitudeView;
	private double longitude = 0;
	private double latitude = 0;
	private Button photoButton;
	private ImageView mapView;

	// za GPS podesavanja
	LocationManager lm;
	Location location;

	final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			showCurrentLocation();
		}

		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			showCurrentLocation();
		}

		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			showCurrentLocation();
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo);

		this.imageView = (ImageView) this.findViewById(R.id.imageView1);
		this.dateView = (TextView) findViewById(R.id.datum);
		this.fileView = (TextView) findViewById(R.id.nazivSlike);
		this.photoButton = (Button) this.findViewById(R.id.button1);
		this.longitudeView = (TextView) findViewById(R.id.longitude);
		this.latitudeView = (TextView) findViewById(R.id.latitude);
		this.mapView = (ImageView) findViewById(R.id.imageView2);

		// GPS podesavanja

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10,
				locationListener);

		checkGPS();
		//

		photoButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, CAMERA_REQUEST);
			}
		});

	}

	public void checkGPS() {
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS is Enabled in your device",
					Toast.LENGTH_SHORT).show();
			photoButton.setEnabled(true);

			// showCurrentLocation();

		} else {
			photoButton.setEnabled(false);
			Toast.makeText(this, "You must use GPS", Toast.LENGTH_LONG).show();
			showGPSDisabledAlertToUser();
		}
	}

	public void showCurrentLocation()/* throws UnreadedLocationException */{
		double latitude = location.getLatitude();
		double longitude = location.getLongitude();
		Geocoder myLocation = new Geocoder(getApplicationContext(),
				Locale.getDefault());
		List<Address> myList;
		try {
			myList = myLocation.getFromLocation(latitude, longitude, 1);
			if (myList.size() == 1) {
				// lala.setText(myList.get(0).toString());
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_REQUEST) {
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			imageView.setImageBitmap(photo);

			try {

				if (isExternalStoragePresent()) {

					// create a File object for the parent directory
					File wallpaperDirectory = new File(Environment
							.getExternalStorageDirectory().toString() + "/SNT/");
					// have the object build the directory structure, if needed.
					wallpaperDirectory.mkdirs();
					// create a File object for the output file
					// File outputFile = new File(wallpaperDirectory, "pic_" +
					// Calendar.DAY_OF_MONTH + "_" + Calendar.MONTH + "_" +
					// Calendar.YEAR + "_" + Calendar.HOUR + ":" +
					// Calendar.MINUTE);

					makeJPG(photo);
					
					//uploadToServer(photo);
					this.photo = photo;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		if (data == null) {
			onResume();
		}
	}

	public void makeJPG(Bitmap photo) {

		Date date = new Date();
		String capTime = date.getDate() + "." + date.getMonth() + "."
				+ date.getHours() + " , " + date.getMinutes() + ":"
				+ date.getSeconds();

		String extStorageDirectory = Environment.getExternalStorageDirectory()
				.toString();
		Toast toast = Toast.makeText(this, extStorageDirectory, 3000);
		toast.show();
		OutputStream outStream = null;
		// File file = new File(extStorageDirectory+"/SNT", "pic_" +
		// Calendar.DAY_OF_MONTH + "_" + Calendar.MONTH + "_" + Calendar.YEAR +
		// "_" + Calendar.HOUR + "_" + Calendar.MINUTE + ".jpg");

		File file = new File(extStorageDirectory + "/SNT", "pic_"
				+ date.getDate() + "d_" + date.getMonth() + "m_"
				+ date.getHours() + "h_" + date.getMinutes() + "m_"
				+ date.getSeconds() + "s.jpg");


		try {
			outStream = new FileOutputStream(file);
			photo.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();

			fileView.setText(file.getAbsolutePath());
			dateView.setText(capTime);

			uploadToServer(photo);
			
			makeMapJPG(date, extStorageDirectory);
		} catch (Exception e) {
		}

	}

	public void makeMapJPG(Date date, String extStorageDirectory) {

		
		this.longitude = location.getLongitude();
		this.latitude = location.getLatitude();

		String s = "map_" + date.getDate() + "d_" + date.getMonth() + "m_"
				+ date.getHours() + "h_" + date.getMinutes() + "m_"
				+ date.getSeconds() + "s.jpg";

		DownloadMapFromUrl(
				"http://maps.googleapis.com/maps/api/staticmap?size=420x420&scale=1&format=jpg&maptype=roadmap&sensor=false&markers=color:red%7C"
						+ latitude + "," + longitude, s);
		this.longitudeView.setText(longitude + "");
		this.latitudeView.setText(latitude + "");

		Bitmap bitmap = BitmapFactory.decodeFile(extStorageDirectory + "/" + s);
		this.mapView.setImageBitmap(bitmap);
		
		//uploadToServer(bitmap);
		this.mapPhoto = bitmap;
	}

	private boolean isExternalStoragePresent() {

		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) {
			Toast.makeText(this, "SD card not present", Toast.LENGTH_LONG)
					.show();

		}
		return (mExternalStorageAvailable) && (mExternalStorageWriteable);
	}

	public void DownloadMapFromUrl(String DownloadUrl, String fileName) {

		try {
			File root = android.os.Environment.getExternalStorageDirectory();

			// File dir = new File (root.getAbsolutePath() + "/xmls");
			File dir = new File(root.getAbsolutePath());
			if (dir.exists() == false) {
				dir.mkdirs();
			}

			URL url = new URL(DownloadUrl); // you can write here any link
			File file = new File(dir, fileName);

			long startTime = System.currentTimeMillis();
			Log.i("DownloadManager", "download begining");
			Log.i("DownloadManager", "download url:" + url);
			Log.i("DownloadManager", "downloaded file name:" + fileName);

			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();

			/*
			 * Define InputStreams to read from the URLConnection.
			 */
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */
			ByteArrayBuffer baf = new ByteArrayBuffer(5000);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			/* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.flush();
			fos.close();
			Log.d("DownloadManager",
					"download ready in"
							+ ((System.currentTimeMillis() - startTime) / 1000)
							+ " sec");

		} catch (IOException e) {
			Log.d("DownloadManager", "Error: " + e);
		}

		//uploadToServer(mapPhoto);
		uploadToServer(photo);
		
		
	}

	private void showGPSDisabledAlertToUser() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder
				.setMessage(
						"GPS is disabled in your device. Would you like to enable it?")
				.setCancelable(false)
				.setPositiveButton("Goto Settings Page To Enable GPS",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent callGPSSettingIntent = new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								startActivity(callGPSSettingIntent);
								photoButton.setEnabled(true);
							}
						});
		alertDialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						finish();
					}
				});
		AlertDialog alert = alertDialogBuilder.create();
		alert.show();
	}

	public void uploadToServer(Bitmap photo) {
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

		/*
		 * String weight = "3700"; String fromUnit = "Grams"; String toUnit =
		 * "Kilograms";
		 * 
		 * PropertyInfo weightProp =new PropertyInfo();
		 * weightProp.setName("Weight"); weightProp.setValue(weight);
		 * weightProp.setType(double.class); request.addProperty(weightProp);
		 * 
		 * PropertyInfo fromProp =new PropertyInfo();
		 * fromProp.setName("FromUnit"); fromProp.setValue(fromUnit);
		 * fromProp.setType(String.class); request.addProperty(fromProp);
		 * 
		 * PropertyInfo toProp =new PropertyInfo(); toProp.setName("ToUnit");
		 * toProp.setValue(toUnit); toProp.setType(String.class);
		 * request.addProperty(toProp);
		 */

		Bitmap bitmapOrg = photo;
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
		byte[] ba = bao.toByteArray();
		String encodedString = Base64.encodeBytes(ba);

		request.addProperty("fileName", "slika.jpg");
		request.addProperty("encodedString", encodedString);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.implicitTypes = true; // ovo je neophodno da se izbjegne
										// i:type=\"d:int\" u envelopi!!!
		envelope.setAddAdornments(false);
		envelope.setOutputSoapObject(request); // ovo je neophodno da se
												// izbjegne id=\oO\"
												// c:root=\"1\" u envelopi!!!
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject response = (SoapObject) envelope.bodyIn;
			String sum = response.getProperty(0).toString();

			Log.i("AndroidWebService", sum);

			TextView tv = new TextView(this);
			// tv.setText(weight+" "+fromUnit+" equal "+response.toString()+
			// " "+toUnit);
			tv.setText("Rezultat: " + sum);
			setContentView(tv);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
